package com.tek.ding.faceding.network.rx;

import android.content.Context;
import android.widget.Toast;

import com.google.gson.JsonSyntaxException;
import com.tek.ding.faceding.network.exception.ApiException;
import com.tek.ding.faceding.network.exception.BaseException;
import com.tek.ding.faceding.network.exception.ErrorMessageFactory;

import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;

public class RxErrorHandle {

    private Context context;

    public RxErrorHandle(Context context) {
        this.context = context;
    }

    public BaseException handleError(Throwable e) {
        BaseException baseException = new BaseException();

        if (e instanceof ApiException) {
            baseException.setStatus(((ApiException) e).getStatus());
        } else if (e instanceof SocketException) {
            baseException.setStatus(BaseException.SOCKET_ERROR);
        } else if (e instanceof SocketTimeoutException) {
            baseException.setStatus(BaseException.SOCKET_TIMEOUT_ERROR);
        } else if (e instanceof HttpException) {
            baseException.setStatus(BaseException.HTTP_ERROR);
        } else if (e instanceof NullPointerException) {
            baseException.setStatus(BaseException.NULL_ERROR);
        } else if (e instanceof JsonSyntaxException) {
            baseException.setStatus(BaseException.JSON_ERROR);
        } else if (e instanceof UnknownHostException) {
            baseException.setStatus(BaseException.NETWORK_ERROR);
        } else {
            baseException.setStatus(BaseException.UNKNOWN_ERROR);
        }

        baseException.setMessage(ErrorMessageFactory.create(context, baseException.getStatus()));
        return baseException;
    }

    public void showErrorMsg(BaseException e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
